<template>
  <div class="complaint-management-container agri-page-container">
    <div class="page-header agri-page-header">
      <div class="page-title agri-page-title">
        <el-icon><Warning /></el-icon>
        <span>投诉管理</span>
      </div>
      <div class="page-actions agri-page-actions">
        <el-button type="primary" @click="handleCreateComplaint">
          <el-icon><Plus /></el-icon> 提交投诉
        </el-button>
      </div>
    </div>

    <!-- 投诉列表 -->
    <el-card v-loading="loading" class="agri-card">
      <template #header>
        <div class="card-header">
          <div class="card-title">投诉列表</div>
          <div class="filter-wrapper">
            <el-select v-model="filterStatus" placeholder="全部状态" clearable @change="handleFilterChange">
              <el-option label="待处理" value="pending" />
              <el-option label="处理中" value="processing" />
              <el-option label="已解决" value="resolved" />
              <el-option label="已关闭" value="closed" />
            </el-select>
          </div>
        </div>
      </template>

      <div v-if="filteredComplaints.length === 0" class="empty-data">
        <el-empty description="暂无投诉记录" />
      </div>
      
      <div v-else>
<div class="agri-table-wrapper">
        <el-table :data="pagedComplaints" border stripe>
          <el-table-column label="订单编号" prop="orderNumber" min-width="180" />
          <el-table-column label="农户名称" prop="farmerName" min-width="120" />
          <el-table-column label="投诉标题" prop="title" min-width="180" />
          <el-table-column label="投诉时间" min-width="120">
            <template #default="scope">
              {{ formatDate(scope.row.createDate) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
        <div class="agri-operations">
          <el-button type="primary" size="small" @click="handleViewComplaint(scope.row)">
                查看
              </el-button>
            
        </div>
      </template>
          </el-table-column>
        </el-table>
</div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="filteredComplaints.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 创建投诉对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="提交投诉"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="complaintFormRef"
        :model="complaintForm"
        :rules="complaintRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="订单" prop="orderId">
          <el-select
            v-model="complaintForm.orderId"
            filterable
            placeholder="请选择订单"
            style="width: 100%"
            @change="handleOrderChange"
          >
            <el-option
              v-for="order in orders"
              :key="order.id"
              :label="order.orderNumber + ' - ' + order.productName"
              :value="order.id"
            >
              <div class="order-option">
                <div class="order-option-left">
                  <div class="order-number">{{ order.orderNumber }}</div>
                  <div class="order-product">{{ order.productName }}</div>
                </div>
                <div class="order-option-right">
                  <div class="order-time">{{ formatDate(order.orderDate) }}</div>
                  <div class="order-farmer">{{ order.farmerName }}</div>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="投诉标题" prop="title">
          <el-input v-model="complaintForm.title" placeholder="请输入投诉标题" />
        </el-form-item>

        <el-form-item label="投诉类型" prop="type">
          <el-select v-model="complaintForm.type" placeholder="请选择投诉类型" style="width: 100%">
            <el-option label="商品质量问题" value="quality" />
            <el-option label="物流配送问题" value="delivery" />
            <el-option label="售后服务问题" value="service" />
            <el-option label="商品描述不符" value="description" />
            <el-option label="其他问题" value="other" />
          </el-select>
        </el-form-item>

        <el-form-item label="投诉内容" prop="content">
          <el-input
            v-model="complaintForm.content"
            type="textarea"
            :rows="4"
            placeholder="请详细描述您的问题..."
          />
        </el-form-item>

        <el-form-item label="上传图片" prop="images">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="5"
            :on-change="handleImageChange"
            :file-list="fileList"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">可上传jpg/png图片，不超过2MB，最多5张</div>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="complaintForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitComplaint" :loading="submitLoading">提交投诉</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 投诉详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="投诉详情"
      width="700px"
    >
      <div v-if="currentComplaint" class="complaint-detail">
        <div class="complaint-header">
          <h3 class="complaint-title">{{ currentComplaint.title }}</h3>
          <el-tag :type="getStatusType(currentComplaint.status)" class="complaint-status">
            {{ getStatusText(currentComplaint.status) }}
          </el-tag>
        </div>

        <el-descriptions :column="2" border class="complaint-info">
          <el-descriptions-item label="订单编号">{{ currentComplaint.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="投诉时间">{{ formatDate(currentComplaint.createDate) }}</el-descriptions-item>
          <el-descriptions-item label="农户名称">{{ currentComplaint.farmerName }}</el-descriptions-item>
          <el-descriptions-item label="投诉类型">{{ getComplaintTypeText(currentComplaint.type) }}</el-descriptions-item>
          <el-descriptions-item label="商品名称" :span="2">{{ currentComplaint.productName }}</el-descriptions-item>
        </el-descriptions>

        <div class="complaint-section">
          <h4 class="section-title">投诉内容</h4>
          <p class="complaint-content">{{ currentComplaint.content }}</p>
        </div>

        <div v-if="currentComplaint.images && currentComplaint.images.length > 0" class="complaint-section">
          <h4 class="section-title">证据图片</h4>
          <div class="complaint-images">
            <el-image
              v-for="(img, index) in currentComplaint.images"
              :key="index"
              :src="img"
              :preview-src-list="currentComplaint.images"
              fit="cover"
              class="evidence-image"
            />
          </div>
        </div>

        <div v-if="currentComplaint.replyContent" class="complaint-section reply-section">
          <h4 class="section-title">商家回复 <span class="reply-time">{{ formatDate(currentComplaint.replyDate) }}</span></h4>
          <p class="reply-content">{{ currentComplaint.replyContent }}</p>
        </div>

        <div v-if="currentComplaint.status === 'resolved'" class="complaint-section solution-section">
          <h4 class="section-title">解决方案</h4>
          <p class="solution-content">{{ currentComplaint.solution || '问题已解决' }}</p>
          <div class="resolve-time">解决时间: {{ formatDate(currentComplaint.resolveDate) }}</div>
        </div>

        <div class="complaint-actions" v-if="currentComplaint.status !== 'closed' && currentComplaint.status !== 'resolved'">
          <el-button type="primary" @click="handleFollowUp">跟进投诉</el-button>
          <el-button @click="handleCloseComplaint">关闭投诉</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 跟进投诉对话框 -->
    <el-dialog
      v-model="followUpDialogVisible"
      title="跟进投诉"
      width="500px"
    >
      <el-form
        ref="followUpFormRef"
        :model="followUpForm"
        :rules="followUpRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="跟进内容" prop="content">
          <el-input
            v-model="followUpForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入跟进内容..."
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="followUpDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitFollowUp" :loading="followUpLoading">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Warning, Plus
} from '@element-plus/icons-vue';
import { useBuyerStore } from '../../store';
import { format } from 'date-fns';
import { useUserStore } from '../../store';

// 状态管理
const buyerStore = useBuyerStore();
const userStore = useUserStore();

// 列表数据
const loading = ref(false);
const complaints = ref([]);
const orders = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const filterStatus = ref('');

// 对话框控制
const createDialogVisible = ref(false);
const detailDialogVisible = ref(false);
const followUpDialogVisible = ref(false);
const currentComplaint = ref(null);
const submitLoading = ref(false);
const followUpLoading = ref(false);
const fileList = ref([]);

// 投诉表单
const complaintFormRef = ref(null);
const followUpFormRef = ref(null);
const complaintForm = reactive({
  orderId: '',
  title: '',
  type: '',
  content: '',
  images: [],
  phone: ''
});

// 跟进表单
const followUpForm = reactive({
  content: ''
});

// 表单验证规则
const complaintRules = {
  orderId: [
    { required: true, message: '请选择订单', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入投诉标题', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择投诉类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入投诉内容', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

const followUpRules = {
  content: [
    { required: true, message: '请输入跟进内容', trigger: 'blur' },
    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
  ]
};

// 过滤后的投诉列表
const filteredComplaints = computed(() => {
  if (!complaints.value.length) return [];
  if (!filterStatus.value) return complaints.value;
  
  return complaints.value.filter(complaint => 
    complaint.status === filterStatus.value
  );
});

// 分页后的投诉列表
const pagedComplaints = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredComplaints.value.slice(start, end);
});

// 获取状态类型样式
const getStatusType = (status) => {
  const types = {
    'pending': 'warning',
    'processing': 'primary',
    'resolved': 'success',
    'closed': 'info'
  };
  return types[status] || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'pending': '待处理',
    'processing': '处理中',
    'resolved': '已解决',
    'closed': '已关闭'
  };
  return texts[status] || '未知状态';
};

// 获取投诉类型文本
const getComplaintTypeText = (type) => {
  const texts = {
    'quality': '商品质量问题',
    'delivery': '物流配送问题',
    'service': '售后服务问题',
    'description': '商品描述不符',
    'other': '其他问题'
  };
  return texts[type] || '未知类型';
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  return format(new Date(date), 'yyyy-MM-dd HH:mm');
};

// 筛选状态变化
const handleFilterChange = () => {
  currentPage.value = 1;
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 创建投诉
const handleCreateComplaint = async () => {
  // 获取订单列表
  try {
    loading.value = true;
    const ordersData = await buyerStore.fetchOrders();
    orders.value = ordersData.filter(order => 
      // 只显示已完成和已发货的订单
      ['completed', 'shipped'].includes(order.status)
    );
    
    // 重置表单
    resetComplaintForm();
    createDialogVisible.value = true;
  } catch (error) {
    console.error('获取订单列表失败', error);
    ElMessage.error('获取订单列表失败');
  } finally {
    loading.value = false;
  }
};

// 订单选择变化
const handleOrderChange = (orderId) => {
  if (!orderId) return;
  
  const selectedOrder = orders.value.find(order => order.id === orderId);
  if (selectedOrder) {
    // 自动填充电话
    complaintForm.phone = selectedOrder.phone || '';
  }
};

// 图片上传变化
const handleImageChange = (file, fileList) => {
  // 图片格式限制
  const isJPG = file.raw.type === 'image/jpeg';
  const isPNG = file.raw.type === 'image/png';
  const isLt2M = file.raw.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
    fileList.pop();
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
    fileList.pop();
    return false;
  }
  
  // 使用FileReader读取文件
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    // 将Base64字符串保存到表单
    complaintForm.images.push(reader.result);
  };
};

// 提交投诉
const submitComplaint = async () => {
  if (!complaintFormRef.value) return;
  
  await complaintFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      submitLoading.value = true;
      
      // 获取订单详情
      const selectedOrder = orders.value.find(order => order.id === complaintForm.orderId);
      
      // 准备投诉数据
      const complaintData = {
        orderId: complaintForm.orderId,
        orderNumber: selectedOrder.orderNumber,
        farmerId: selectedOrder.farmerId,
        farmerName: selectedOrder.farmerName,
        productName: selectedOrder.productName,
        title: complaintForm.title,
        type: complaintForm.type,
        content: complaintForm.content,
        images: complaintForm.images,
        phone: complaintForm.phone
      };
      
      // 提交投诉
      await buyerStore.createComplaint(complaintData);
      
      createDialogVisible.value = false;
      
      // 刷新投诉列表
      fetchComplaints();
    } catch (error) {
      console.error('提交投诉失败', error);
      ElMessage.error('提交投诉失败: ' + (error.message || '未知错误'));
    } finally {
      submitLoading.value = false;
    }
  });
};

// 重置投诉表单
const resetComplaintForm = () => {
  if (complaintFormRef.value) {
    complaintFormRef.value.resetFields();
  }
  Object.assign(complaintForm, {
    orderId: '',
    title: '',
    type: '',
    content: '',
    images: [],
    phone: ''
  });
  fileList.value = [];
};

// 查看投诉详情
const handleViewComplaint = async (complaint) => {
  try {
    loading.value = true;
    // 获取完整的投诉详情
    const complaintDetail = await buyerStore.getComplaintDetail(complaint.id);
    if (complaintDetail) {
      currentComplaint.value = complaintDetail;
      detailDialogVisible.value = true;
    }
  } catch (error) {
    console.error('获取投诉详情失败', error);
    ElMessage.error('获取投诉详情失败');
  } finally {
    loading.value = false;
  }
};

// 跟进投诉
const handleFollowUp = () => {
  followUpForm.content = '';
  followUpDialogVisible.value = true;
};

// 提交跟进
const submitFollowUp = async () => {
  if (!followUpFormRef.value) return;
  
  await followUpFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      followUpLoading.value = true;
      
      // 调用API
      await buyerStore.followUpComplaint(currentComplaint.value.id, followUpForm.content);
      
      followUpDialogVisible.value = false;
      detailDialogVisible.value = false;
      
      // 刷新投诉列表
      fetchComplaints();
    } catch (error) {
      console.error('提交跟进失败', error);
      ElMessage.error('提交跟进失败: ' + (error.message || '未知错误'));
    } finally {
      followUpLoading.value = false;
    }
  });
};

// 关闭投诉
const handleCloseComplaint = () => {
  ElMessageBox.confirm(
    '确定要关闭此投诉吗？',
    '关闭投诉',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 调用API
      await buyerStore.closeComplaint(currentComplaint.value.id);
      
      detailDialogVisible.value = false;
      
      // 刷新投诉列表
      fetchComplaints();
    } catch (error) {
      console.error('关闭投诉失败', error);
      ElMessage.error('关闭投诉失败: ' + (error.message || '未知错误'));
    }
  }).catch(() => {});
};

// 获取投诉列表
const fetchComplaints = async () => {
  loading.value = true;
  try {
    // 检查用户角色
    if (!userStore.isBuyer) {
      ElMessage.warning('只有买家才能访问投诉管理页面');
      complaints.value = [];
      return;
    }
    
    console.log('开始获取投诉列表，当前用户角色:', userStore.getRole);
    const complaintsData = await buyerStore.fetchComplaints();
    console.log('获取到投诉数据:', complaintsData);
    complaints.value = complaintsData || [];
  } catch (error) {
    console.error('获取投诉列表失败', error);
    if (error.message === '无权限访问') {
      ElMessage.error('您没有权限访问投诉管理功能，请联系管理员');
    } else {
      ElMessage.error('获取投诉列表失败: ' + (error.message || '未知错误'));
    }
    complaints.value = [];
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchComplaints();
});
</script>

<style scoped>
.complaint-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.page-title .el-icon {
  margin-right: 8px;
  font-size: 24px;
  color: var(--primary-color);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: bold;
  font-size: 16px;
}

.filter-wrapper {
  width: 200px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.complaint-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.complaint-title {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.complaint-info {
  margin-bottom: 20px;
}

.complaint-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding-bottom: 10px;
  color: var(--primary-color);
}

.reply-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  font-weight: normal;
  margin-left: 10px;
}

.complaint-content,
.reply-content,
.solution-content {
  white-space: pre-wrap;
  line-height: 1.6;
}

.reply-section {
  background-color: #f6f9fc;
  padding: 15px;
  border-radius: 4px;
}

.solution-section {
  background-color: #f0f9eb;
  padding: 15px;
  border-radius: 4px;
}

.resolve-time {
  margin-top: 10px;
  color: var(--el-text-color-secondary);
  font-size: 12px;
  text-align: right;
}

.complaint-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.evidence-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}

.complaint-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.order-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.order-option-left {
  text-align: left;
}

.order-option-right {
  text-align: right;
}

.order-number {
  font-weight: bold;
}

.order-product {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.order-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.order-farmer {
  font-size: 12px;
}

.upload-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 5px;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .filter-wrapper {
    width: 100%;
  }
  
  .complaint-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style> 